import React from 'react';
import { observer } from 'mobx-react';
import {
  Form,
  Select,
} from 'choerodon-ui/pro';
import {
  organizationsApi,
} from '@choerodon/master';
import { useBatchEditStore } from './stores';
import './index.less';

const prefix = 'c7ncd-batch-edit';

const Index = observer(() => {
  const {
    selected,
    FormDataSet,
    modal,
    refresh,
  } = useBatchEditStore();

  const handleOk = async () => {
    const flag = await FormDataSet.validate();
    if (flag) {
      const data = {
        userId: selected.map((item: any) => item.get('id')),
        roleIds: FormDataSet?.current?.get('roleIds').map((i: any) => i?.id),
        userLabels: FormDataSet?.current?.get('userLabels')?.map((i: any) => i?.name) || [],
      };
      try {
        await organizationsApi.batchUpdate(data);
        refresh && refresh();
        return true;
      } catch (e) {
        console.log(e);
        return false;
      }
    }
    return flag;
  };

  if (modal) {
    modal.handleOk(handleOk);
  }

  return (
    <div className={prefix}>
      <p className={`${prefix}-title`}>
        {selected.length}
        项已选中
      </p>
      <Form dataSet={FormDataSet}>
        <Select name="roleIds" />
        <Select combo name="userLabels" />
      </Form>
    </div>
  );
});

export default Index;
